# -*- coding: utf-8 -*-

"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 菜单按钮管理
"""
from dvadmin.system.models import MenuButton
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from dvadmin.utils.json_response import SuccessResponse


class MenuButtonSerializer(CustomModelSerializer):
    """
    菜单按钮-序列化器
    """

    class Meta:
        model = MenuButton
        fields = "__all__"
        read_only_fields = ["id"]



class NewMenuButtonSerializer(CustomModelSerializer):
    """
    菜单按钮-序列化器
    """


    class Meta:
        model = MenuButton
        fields = "__all__"
        read_only_fields = ["id"]



class MenuButtonViewSet(CustomModelViewSet):
    """
    菜单按钮接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = MenuButton.objects.all()
    serializer_class = MenuButtonSerializer
    extra_filter_backends = []


    @action(methods=['PUT'], detail=False)
    def onecreate(self, request):
        """
        一键生成
        """
        # url = request.query_params['url']
        # print(url)


        data = [{'name':"详情",'value':'Retrieve','api':'','method':0},
                {'name': "编辑", 'value': 'Update', 'api': '', 'method': 2},
                {'name': "查询", 'value': 'Search', 'api': '', 'method': 0},
                {'name': "新增", 'value': 'Create', 'api': '', 'method': 1},
                {'name': "删除", 'value': 'Delete', 'api': '', 'method': 3},
                ]
        for i in data:
            apidata = {}
            prefixdata = request.data['prefix']

            apidata['menu'] = request.data['menu']
            if i['name'] == '详情' or i['name'] == '编辑'  or i['name'] == '删除':
                apidata['api'] = request.data['api'] + '{id}/'
            else:
                apidata['api'] = request.data['api']


            apidata['name'] = i['name']
            apidata['value'] = prefixdata+":"+i['value']
            apidata['method'] = i['method']
            serializer = self.get_serializer(data=apidata, request=request)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)

        return SuccessResponse(msg="获取成功")

